const express = require('express')
const path = require('path')
const resolve = file => path.resolve(__dirname, file)
const config = require(resolve('../config/env'))

const intialRequest = require('../middleware/intial-request')
const fixVirgule = require('../middleware/fix-virgule')
const redirectPath = require('../middleware/redirect-path')
const htmlCache = require('../middleware/html-cache')
const controlRequest = require('../middleware/control-request')
const getConfig = require('../middleware/get-config')
const oldPathRedirect = require('../middleware/oldpath-redirect')
const schedule = require('../schedule/schedule')
const getUserIp = require('../middleware/get-user-ip')
const staticServer = require('./static')
const proxyServer = require('./proxy')

const vueSSR = require('./vue.ssr')

const app = express()

/*全局初始化，并处理异常请求*/
app.use(intialRequest)

// 代理请求接口
proxyServer(app)

//静态资源代理
staticServer(app)

// 非本地环境开启定时任务
if (!config.environment.includes('isLocal')) {
  // 关闭定时任务生成死链文件
  schedule.startSchedule()
} 

// 服务器端渲染
vueSSR(app)
 
//错误处理中间件
app.use((err, req, res, next) => {
  // js-ignore
  console.log('Time:' + parseInt(Date.now() / 1000), 'express error handler url:' + req.url, err)
  res.status(500).end('500 | Internal Server Error')
})
const port = config.port || 3002
// 指定host为127.0.0.1
const host = '0.0.0.0'
let webserver = app.listen(port, host, () => {
  // js-ignore
  console.log('\x1b[33m%s\x1b[0m', `server started at localhost:${port}`)
}) 

//捕获进程级别的错误日志
process.on('uncaughtException', err =>
// js-ignore
  console.log('Time:' + parseInt(Date.now() / 1000), 'process uncaught Exception', err)
)
// 进程名称
process.title = config.processTitle
// 平滑启动测试环境3s,正式30s
let time = config.environment === 'isProd' ? 10000 : 3000
//平滑重启的核心代码
process.on('SIGINT', () => {
  //10秒后强制关闭本进程
  setTimeout(() => {
    process.exit(0)
  }, time)

  //不再接受新的请求
  webserver.close()
})
// // 在本地运行时，需要将pre-commit拷贝到.git/hooks目录下
// if (config && config.environment.toLowerCase().includes('local')) {
//   try {
//     const fs = require('fs')
//     let preCommitPath = path.resolve(__dirname, '../hooks/pre-commit')
//     let dstPath = path.resolve(__dirname, '../.git/hooks/pre-commit')
//     fs.copyFileSync(preCommitPath, dstPath)
//     // js-ignore
//     console.log('pre-commit copied~') 
//   } catch (e) {
//     // js-ignore
//     console.log('error', e)
//   }
// }
